import {useEffect, useState} from "react";
import {Button, List, Space, Tag} from "antd";

const cacheKey = "gitee-repository"
const username = "slowlyo"

// 根据 Star 数量排序
const sortByStar = (list) => list.sort((a, b) => b.stargazers_count - a.stargazers_count)

// 根据是否有 Pages 排序
const sortByHasPage = (list) => list.sort((a, b) => b.has_page - a.has_page)

// 获取所有公开仓库
const fetchData = async () => {
    const cachedData = sessionStorage.getItem(cacheKey)
    if (cachedData) {
        return JSON.parse(cachedData)
    }

    let page = 1
    let repos = []

    // 获取所有公开仓库
    const fetchRepo = async () => {
        const params: any = {type: "all", sort: "full_name", page, per_page: 100}
        const api = `https://gitee.com/api/v5/users/${username}/repos?` + new URLSearchParams(params)
        const res = await fetch(api, {method: "GET"}).then(res => res.json())
        repos = repos.concat(res)
        if (res.length === 100) {
            page++
            await fetchRepo()
        }
    }

    await fetchRepo()

    sessionStorage.setItem(cacheKey, JSON.stringify(sortByStar(sortByHasPage(repos))))

    return repos
}

// Gitee 仓库列表
const GiteeRepository = () => {
    const [data, setData] = useState([])
    const [loading, setLoading] = useState(true)

    const pagesAction = (item) => {
        const path = item.path == username ? "" : item.path
        const pagesUrl = `https://${username}.gitee.io/${path}`

        return item.has_page ? <Button type="link" onClick={() => window.open(pagesUrl)}>Pages</Button> : null
    }

    const listTitle = (item) => {
        return (
            <div className="flex items-center">
                <a className='font-bold text-[16px] !text-blue-500' href={item.html_url} target="_blank">{item.name}</a>
                <Space className="ml-3">
                    {item.stargazers_count > 0 && <Tag color="warning">Star {item.stargazers_count}</Tag>}
                    {item.language && <Tag color="processing">{item.language}</Tag>}
                </Space>
            </div>
        )
    }

    useEffect(() => {
        setData([])
        fetchData().then(res => {
            setData(res)
            setLoading(false)
        })
    }, [])

    return (
        <div>
            <List loading={loading} dataSource={data} renderItem={(item) => {
                return (
                    <List.Item actions={[pagesAction(item)]}>
                        <List.Item.Meta
                            title={listTitle(item)}
                            description={item.description}
                        />
                    </List.Item>
                )
            }}/>
        </div>
    )
};

export default GiteeRepository;
